package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.consatnts.message.PublishArticleConstants;
import com.heima.common.consatnts.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;


/**
 * author by itheima
 *
 * @Date 2022/3/4
 * Description
 */
@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 自动审核方法
     *
     * @param wmNewsId
     */
    @Override
    public void autoScanWmNews(Integer wmNewsId) {
        //1.根据文章id 远程调用feign查询文章
        if (wmNewsId == null) {
            log.error("自动审核文章失败  文章id为空", wmNewsId);
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断自媒体文章是否存在 根据id查询文章信息
        WmNews wmNews = wmNewsMapper.selectById(wmNewsId);
        if (wmNews == null) {
            log.error("未查询自媒体文章信息", wmNewsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.判断文章状态是否为待审核状态   状态：1
        Short status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(status)) {
            log.error("文章的审核状态不为1  id{}", wmNewsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章不是待审核状态");
        }
        //抽取出文章的所有  文本内容  和  图片 url
        Map<String, Object> contentAndImageResult = handleTextAndImage(wmNews);
        //敏感词审核  失败  修改文章状态（2）
        boolean isSensitive = handleSensitive((String) contentAndImageResult.get("content"), wmNews);
        if (!isSensitive) {
            log.error("文章中存在敏感词 ");
            return;
        }
        // 阿里云 文本审核   block：2   review：3
        boolean isTextSensitive = handleTextScan((String) contentAndImageResult.get("content"), wmNews);
        if (!isTextSensitive) {
            log.error("阿里云文本审核不过关");
            return;
        }
        //图片审核
        List<String> images = (List<String>) contentAndImageResult.get("images");
        if (!CollectionUtils.isEmpty(images)) {
            boolean isImagesSensitive = handleImagesScan(images, wmNews);
            if (!isImagesSensitive) {
                log.error("阿里云图片审核不过关");
                return;
            }
        }
        //   状态8
        updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "阿里云远程调用成功，审核成功");
        // TODO 延时发布任务   用于文章发布
        //发布时间
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message) -> {                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
    }

    /**
     * 阿里云图片审核
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        boolean flag = false;
        try {
            Map map = greenImageScan.imageUrlScan(images);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "阿里云图片审核失败");
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "转为人工审核");
                case "pass":
                    flag = true;
                    break;
            }
            //       updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "阿里云图片审核成功");
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云远程调用失败，转为人工审核");
        }
        return flag;
    }

    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 阿里云 文章审核
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = false;
        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章审核不过关");
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "待人工审核");
                case "pass":
                    flag = true;
                    break;
            }
            //    updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "文章的文本内容审核成功");
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核调用失败，转为人工审核");
        }
        return flag;
    }

    @Autowired
    private AdminFeign adminFeign;

    /**
     * 基于DFA 检测内容是否包含敏感词
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        //1.远程查询敏感词列表
        ResponseResult<List<String>> sensitives = adminFeign.sensitives();
        if (!sensitives.checkCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        //2.基于DFA审核内容中是否包含敏感词
        List<String> data = sensitives.getData();
        if (!CollectionUtils.isEmpty(data)) {
            SensitiveWordUtil.initMap(data);
            Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(content);
            //3.如果包含敏感词   将文章  状态改为2  设置原因
            if (!CollectionUtils.isEmpty(stringIntegerMap)) {
                updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "包含敏感词");
                flag = false;
            }
        }


        return flag;
    }

    /**
     * 修改文章状态
     *
     * @param wmNews
     * @param code
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short code, String reason) {
        wmNews.setStatus(code);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    @Value("${file.oss.web-site}")
    String website;

    /**
     * 抽取文章中所有  文本内容和   所有图片路径
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImage(WmNews wmNews) {
        String contentJson = wmNews.getContent();
        if (StringUtils.isBlank(contentJson)) {
            log.info("自动审核文章失败     文章内容为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<Map> contentMaps = JSONArray.parseArray(contentJson, Map.class);
        //抽取文章中所有文本
        String content = contentMaps.stream().filter(map -> "text".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .collect(Collectors.joining(","));
        //文章 的文本加标题
        content = content + "," + wmNews.getTitle();


        //抽取文章中所有的图片      文本里的图片和 封面里的图片
        List<String> images = contentMaps.stream().filter(map -> "image".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .collect(Collectors.toList());
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            // 按照 逗号 切割封面字符串  得到数组   基于数组得到stream   将每一条数据都拼接一个前缀 收集成集合
            //stream()中有数组，集合 和Stream.of
            List<String> urls = Arrays.stream(wmNews.getImages().split(","))
                    //路径 是 前缀加url
                    .map(url -> website + url)
                    .collect(Collectors.toList());
            images.addAll(urls);
        }
        //所有图片去重
        images = images.stream().distinct().collect(Collectors.toList());
        Map map = new HashMap<>();
        map.put("content", content);
        map.put("images", images);
        return map;
    }

}
